package com.sinodata.bsm.cicp.collector.informix;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.Collector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.CommandReader;
import com.sinodata.bsm.cicp.util.ProtocolParameterUtil;
import com.sinodata.bsm.common.constants.SeparatorConstants;
import com.sinodata.bsm.common.vo.ProtocolParameter;
import com.sinodata.bsm.common.vo.ResPropertyValue;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author Administrator
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2013-1-15 下午4:14:29          Administrator        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class OnlineLogCollector extends Collector {
    private static Logger logger = Logger.getLogger(OnlineLogCollector.class);

    @Override
    public String[] getPropMeta() {
        return new String[] { "$1", "$2" };
    }

    @Override
    public String[] getParamMeta() {
        return new String[] { "FilePath", "ErrorFlag" };
    }

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        String filePath = this.getParamMap().get("FilePath").trim();
        String errFlag = this.getParamMap().get("ErrorFlag").trim();
        ProtocolParameter protocolParameter = ProtocolParameterUtil.getHostValue(ip);
        String filterDir = protocolParameter.getUrl();
        //获取上次文件大小
        Long lastFileSize = null;
        try {
            lastFileSize = (Long) this.getPersistentData(ip + "_" + filePath);
        } catch (IOException e) {
            logger.error("OnlineLogCollector product error:IOException when get last file size");
            throw new CollectorException(e);
        } catch (ClassNotFoundException e) {
            logger.error("OnlineLogCollector product error when last file size exchange to Long");
            throw new CollectorException(e);
        }
        //获取现在文件大小
        Long currFileSize = null;
        String cmd = getFileSizeCmd(filterDir, filePath);
        BufferedReader reader = null;
        try {
            reader = CommandReader.getReader(ip, cmd, 0, 0);
            String strLine = null;
            if (reader != null && (strLine = reader.readLine()) != null) {
                currFileSize = Long.parseLong(strLine.trim());
            }
        } catch (IOException e) {
            logger.error("OnlineLogCollector product error when execute cmd:" + cmd);
            throw new CollectorException(e);
        }
        if (currFileSize == null) {
            logger.error("currFileSize is null,return null");
            return null;
        }
        List<ResPropertyValue> result = null;
        String[] propMetas = getPropMeta();
        ResPropertyValue propertyValueX = new ResPropertyValue();
        ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];
        if (lastFileSize != null) {
            if (lastFileSize < currFileSize) {
                result = readFile(ip, filterDir, filePath, errFlag, lastFileSize);
            } else if (lastFileSize > currFileSize) {
                result = readFile(ip, filterDir, filePath, errFlag, new Long(0));
            } else {
                result = new ArrayList<ResPropertyValue>();
                propValues[0] = ResPropertyValue.createPropValue("无", propMetas[0]);
                propValues[1] = ResPropertyValue.createPropValue(" ", propMetas[1]);
                propertyValueX.setValues(propValues);
                result.add(propertyValueX);
            }
        }
        // 记录文件大小
        try {
            this.savePersistentData(ip + "_" + filePath, currFileSize);
        } catch (IOException e) {
            logger.error("OnlineLogCollector produc error where save currFileSize");
            throw new CollectorException(e);
        }
        return result;
    }

    /**
     * @param ip
     * @param filePath
     * @param errFlag
     * @param lastFileSize
     * @return
     * @throws CollectorException 
     */
    private List<ResPropertyValue> readFile(String ip, String filterDir, String filePath, String errFlag, Long lastFileSize) throws CollectorException {
        String cmd = "";
        if (filterDir != null && !filterDir.equals("")) {
            filterDir = filterDir.trim();
            if (!filterDir.endsWith("/")) {
                filterDir += "/";
            }
            cmd = filterDir + "filter -f " + filePath + " -s " + lastFileSize + " -p '" + errFlag + "'";
        } else {
            cmd = "filter -f " + filePath + " -s " + lastFileSize + " -p '" + errFlag + "'";
        }
        errFlag = errFlag.trim().replace("|", "<@>");
        String[] flags = errFlag.split("<@>");
        BufferedReader reader = null;
        String strLine = null;
        StringBuilder sb = new StringBuilder();
        String haveError = "无";
        try {
            reader = CommandReader.getReader(ip, cmd, 0, 0);
            while (reader != null && (strLine = reader.readLine()) != null) {
                for (String flag : flags) {
                    if (strLine.indexOf(flag) > -1) {
                        sb.append(flag).append(SeparatorConstants.COL_SEPARATOR).append(strLine).append(SeparatorConstants.LIN_SEPARATOR);
                        continue;
                    }
                }
            }
            if (sb.length() > 0) {
                haveError = "有";
            }
        } catch (IOException e) {
            logger.error("OnlineLogCollector product error when excute getReader in readFile");
            throw new CollectorException(e);
        }
        List<ResPropertyValue> result = new ArrayList<ResPropertyValue>();
        String[] propMetas = getPropMeta();
        ResPropertyValue propertyValueX = new ResPropertyValue();
        ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];
        propValues[0] = ResPropertyValue.createPropValue(haveError, propMetas[0]);
        propValues[1] = ResPropertyValue.createPropValue(sb.toString(), propMetas[1]);
        propertyValueX.setValues(propValues);
        result.add(propertyValueX);
        return result;
    }

    /**
     * @param filterDir 工作目录
     * @param filePath  文件全路径名
     * @return
     */
    private String getFileSizeCmd(String filterDir, String filePath) {
        String cmd = "";
        if (filterDir != null && !filterDir.equals("")) {
            filterDir = filterDir.trim();
            if (!filterDir.endsWith("/")) {
                filterDir += "/";
            }
            cmd = filterDir + "simls -l " + filePath + " |awk '{print $2}'";
        } else {
            cmd = "simls -l " + filePath + " |awk '{print $2}'";
        }
        return cmd;
    }
}
